﻿using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace RabbitMQ.Extension
{
    public class RabbitConnection
    {
        private bool dispose = false;
        private readonly IConnectionFactory factory;
        private readonly IList<string> hostnames;
        private IConnection conn;
        private Action<Exception> errorAction;
        private Action connectAction;
        private Action closeAction;

        public RabbitConnection(IConnectionFactory factory, IList<string> hostnames = null)
        {
            this.factory = factory;
            this.hostnames = hostnames;
        }

        public void OnError(Action<Exception> action)
        {
            errorAction = action;
        }

        public void OnConnect(Action action)
        {
            connectAction = action;
        }

        public void OnClose(Action action)
        {
            closeAction = action;
        }

        public bool IsOpen()
        {
            if (conn == null)
            {
                return false;
            }
            return conn.IsOpen;
        }

        public void Open()
        {
            dispose = false;
            while (true)
            {
                try
                {
                    if (hostnames == null || hostnames.Count == 0)
                    {
                        conn = factory.CreateConnection();
                    }
                    else
                    {
                        //var hosts = new string[] { "192.168.1.1", "192.168.1.2" }; //集群
                        conn = factory.CreateConnection(hostnames);
                    }
                    connectAction?.Invoke();
                    conn.ConnectionShutdown += (a, b) =>
                    {
                        closeAction?.Invoke();
                        if (dispose)
                        {
                            return;
                        }
                        Task.Factory.StartNew(async () =>
                        {
                            while (true)
                            {
                                if (IsOpen())
                                {
                                    connectAction?.Invoke();
                                    break;
                                }
                                await Task.Delay(2000);
                            }

                        }, TaskCreationOptions.LongRunning);
                    };
                    break;
                }
                catch (Exception ex)
                {
                    errorAction?.Invoke(ex);
                    closeAction?.Invoke();
                }
            }
        }

        public void Close()
        {
            dispose = true;
            conn?.Dispose();
        }

        /// <summary>
        /// 创建通道
        /// </summary>
        /// <returns></returns>
        public IModel CreateChannel()
        {
            return conn.CreateModel();
        }

        /// <summary>
        /// 创建生产者
        /// </summary>
        /// <param name="rabbitType"></param>
        /// <returns></returns>
        public RabbitProducer CreateProducer(RabbitType rabbitType)
        {
            var channel = CreateChannel();
            return new RabbitProducer(rabbitType, channel);
        }

        /// <summary>
        /// 创建消费者
        /// </summary>
        /// <param name="rabbitType"></param>
        /// <returns></returns>
        public RabbitConsumer CreateConsumer(RabbitType rabbitType)
        {
            var channel = CreateChannel();
            return new RabbitConsumer(rabbitType, channel);
        }
    }
}
